package testJdk.commonUse.string.regex;

import org.junit.Test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version 1.0.0
 * Created by cyd on 2023-06-27 11:09:21
 * @ClassName : learn_jdk.commonUse.string.regex.TestRegex
 * @Description : 类描述
 */
public class TestRegex {


    /**
     * 标准用法
     */
    @Test
    public void test01() {
        String example = "This is a small example string";
        // 1、构造表达式对象pattern，“\w+”匹配单词字符
        // 如果想忽略大小写敏感度，可以使用 Pattern.compile("\\s+",Patttern.CASE_INSENSITIVE);
        Pattern pattern = Pattern.compile("\\w+");
        // 2、表达式对象pattern匹配字符串，获得匹配关系Matcher
        Matcher matcher = pattern.matcher(example);
        // 3、matcher.find()
        while (matcher.find()) {
            System.out.print("start index: " + matcher.start());
            System.out.print(" end index: " + matcher.end() + " ");
            System.out.println("group:" + matcher.group());
        }
        // 创建一个新的pattern和matcher以用选项卡替换空格s
        Pattern replace = Pattern.compile("\\s+");
        Matcher matcher2 = replace.matcher(example);
        System.out.println(matcher2.replaceAll("\t"));

    }

    /**
     * 捕获组
     */
    @Test
    public void test02() {
        // 按指定模式在字符串查找
        String line = "This order was placed for QT3000! OK?";
        String regex = "(\\D*)(\\d+)(.*)";

        // 创建 Pattern 对象
        Pattern pattern = Pattern.compile(regex);

        // 现在创建 matcher 对象
        Matcher m = pattern.matcher(line);
        if (m.find()) {
            System.out.println("Found value: " + m.group(0));
            System.out.println("Found value: " + m.group(1));
            System.out.println("Found value: " + m.group(2));
            System.out.println("Found value: " + m.group(3));
        } else {
            System.out.println("NO MATCH");
        }
    }

    /**
     * 简易匹配
     */
    @Test
    public void test03() {
        String phone = "13840588039";
        System.out.println("请输入手机号：" + phone);
        String regex = "1[38]\\d{9}";//用正则表达式定义手机号规则
        boolean flag = phone.matches(regex);
        System.out.println("手机号是否匹配成功：" + flag);
    }

    /**
     * 简易替换
     */
    @Test
    public void test04() {
        String str = "12342javawang2345";
        String regex = "\\d";
        String replaced = "*";
        // 将字符串里面的数字替换成*
        String result = str.replaceAll(regex, replaced);
        System.out.println(result);
    }

}
